﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml;
using System.Reflection;
using System.Windows.Forms;
using LogLib;

namespace KXmlUIControl
{
    public class XmlConfigModule
    {
        /// <summary>
        /// 最新错误信息
        /// </summary>
        public string Error { get; private set; }
        private string _file = "";

        public WindowType FormType = WindowType.ModuleApp;

        private XDocument _xmlDoc = null;

        private XElement _root = null;
      
        public List<XmlPageObject> ListPages = new List<XmlPageObject>();

        private string _homePageName = "";

        public string HomePageName
        {
            get { return _homePageName; }
        }

        private string _startingPageName = "";

        public string StartingPageName
        {
            get { return _startingPageName; }
        }

        public XmlConfigModule(string file)
        {
            _file = file; 
        }

        public bool OnReading()
        {
            if (!OpenXmlDOC())
            {
                return false;
            }
            ListPages = KXmlParser.GetXmlObject<XmlPageObject>(_root, "Pages", "Page");
            GetSpecialTypeName();
            return true;
        }

        private void GetSpecialTypeName()
        {
            XElement node = _root.Element("HomePage");
            if (node != null)
            {
                _homePageName = node.Attribute("TypeName").Value.Trim();
                Log.Write(string.Format("HomePage:TypeName={0}", _homePageName));
            }
            else
            {
                throw new Exception("The home page is null.");
            }

            XElement node1 = _root.Element("StartingPage");
            if (node1 != null)
            {
                _startingPageName = node1.Attribute("TypeName").Value.Trim();
                Log.Write(string.Format("StartingPage:TypeName={0}", _startingPageName));
            }          
        }

        private bool OpenXmlDOC()
        {
            try
            {
                _xmlDoc = XDocument.Load(_file);
                _root = _xmlDoc.Element("Windows");
                string typeVal = _root.Attribute("Type").Value.Trim();
                FormType = (WindowType)Enum.Parse(typeof(WindowType), typeVal);
                return true;
            }
            catch (Exception ex)
            {
                Error = string.Format("配置文件{0}加载错误:{1}", _file, ex.Message);
                Log.WriteException(ex.ToString());
                return false;
            }    
        }
    }
}
